/*
 * Copyright 2011 Christoph Ludwig (christoph[at]chludwig.de). All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package de.chludwig.ehumanities.provenance.background;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * A context listener that inserts a single daemon thread executor into the servlet context and takes care of a 
 * graceful shutdown. 
 * 
 * This code is based on a 
 * <a href="http://stackoverflow.com/questions/4907502/running-a-background-java-program-in-tomcat/4908012#4908012">reply by <it>nos</it></a>
 * to StackOverflow question 4907502.
 */
public class BackgroundThreadContextListener implements ServletContextListener {

  /**
   * Key of the thread executor in the servlet context.
   */
  public static final String BACKGROUND_THREAD_EXECUTOR = "BackgroundThreadExecutor";
  
  private ScheduledExecutorService executor = null;

  /**
   * @return the executor
   */
  public ScheduledExecutorService getExecutor() {
    return executor;
  }

  /* (non-Javadoc)
   * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
   */
  @Override
  public void contextInitialized(ServletContextEvent event) {
    executor  = new ScheduledThreadPoolExecutor(1, new DaemonThreadFactory());
    ServletContext context = event.getServletContext();
    context.setAttribute(BACKGROUND_THREAD_EXECUTOR, executor);
  }

  /* (non-Javadoc)
   * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
   */
  @Override
  public void contextDestroyed(ServletContextEvent event) {
    executor.shutdown();
    try {
      executor.awaitTermination(10, TimeUnit.SECONDS);
      executor.shutdownNow();
    }
    catch (InterruptedException ex) {
      executor.shutdownNow();
      Thread.currentThread().interrupt();
    }
  }

}
